<?php
//include_once('../lib/Dadi/Imgcreatebmp.php');//为了处理php默认不能上传bmp格式的图片

class PictureUpload {
        var $picturesFolder = "dadipics";
        var $picture_url = null;
        var $picture_thumb_url = null;
        var $iconFolder = "icon";
        var $upFileType = "jpg gif png bmp";
        var $upFileMax = 3;
		
        var $fontType;
        var $maxWidth = 500; 
        var $maxHeight = 600; 
        var $isoriginal = 0;
        var $pid;
        var $type;
		var $minWidth = 400;
		var $minHeight = 300;
		protected $_uploadFile = 'uploadfile';
		protected $_savePath = null;
		protected $_saveName = null;
		protected $_pointFolder = 'dadipics';
		protected $_squareFolder = 'squarepic';
        protected $_iconFolder = 'icon';
		protected $_albumFolder = 'album';
		protected $_ntype = 'point';
		protected $_ext = 'jpg';
		protected $_savedPath = null;
        function randomkeys($length){
        	$key='';
        	$pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
   			for($i=0;$i<$length;$i++){
   				$key .= $pattern{rand(0,35)};
   			}
   			return $key;
  	   }
  	   
  	    function error($mes=''){
			json(false,$mes);
			//throw new Dadi_Exception($mes , 300);
        }

		/*上传类型point icon album user*/
        function __construct($ntype = 'point' , $newname = null , $uploadfile = 'uploadfile') {
			$this->_uploadFile = $uploadfile;
			if(@empty($_FILES[$this->_uploadFile]["name"])) $this->error('未找到该name的上传文件');;
			$this->_saveName = empty($newname) ? date('His') .'_' . $this->randomkeys(5) : $newname;
			$this->_ntype = $ntype;
			$this->_savePath = $this->getPath();
			$this->_ext = $this->getFileExt();
			if(is_dir($this->_savePath)==false){
				@mkdir($this->_savePath,0700,1);
			}

            $this->fontType = "../font/msyh.ttf";
//
        }

		public function getPath(){
			switch($this->_ntype){
				case 'point':
					return $this->_pointFolder.DS .date("Y"). DS .date("m"). DS.date("d") . DS;
				break;

				case 'icon':
					$dir1 = floor(intval(Yii::app()->user->id)/1000000);
					$dir2 = floor(intval(Yii::app()->user->id)/1000);
					return $this->_iconFolder . DS . $dir1 . DS . $dir2 . DS;
				break;

				case 'album':
					return $this->_albumFolder.DS .date("Y"). DS .date("m"). DS.date("d") . DS;
				break;
				case 'square':
					return $this->_squareFolder.DS .date("Y"). DS .date("m"). DS.date("d") . DS;
				break;
			}
		}

		public function getSaveFullPath(){
			switch($this->_ntype){
				case 'point':
					$path = $this->_savePath . $this->_saveName . '.' . $this->_ext;
				break;
				case 'icon':
					$path = $this->_savePath . Yii::app()->user->id . '_thumb' ;
				break;

				case 'album':
					$path = $this->_savePath . $this->_saveName . '.' .  $this->_ext;
				break;
				case 'square':
					$path = $this->_savePath . $this->_saveName . '.' .  $this->_ext;
				break;
			}
			return $path;
		}
		
		public function getFileExt(){
			$name = $_FILES[$this->_uploadFile]["name"];
			$name = strtolower($name);
			$path_parts = pathinfo($name);
			$ext = $path_parts['extension'];
			return $ext;
		}

        public function upLoad() {
			if(strpos($this->upFileType,$this->_ext) === false){
				return $this->error("上传文件类型仅支持 ".$this->upFileType." 不支持 ".$imgType);   
			}

			$saveFullPath = $this->getSaveFullPath();//上传后的文件名

			$imgSize = $_FILES[$this->_uploadFile]["size"];
			$kSize = round($imgSize/1024);
			if(!$kSize ||$kSize > ($this->upFileMax*1024)) {
				die($this->error("上传文件不能超过 ".$this->upFileMax."M"));
			}else{
				$upFileok = move_uploaded_file($_FILES[$this->_uploadFile]["tmp_name"],$saveFullPath);
				if(!$upFileok) {
					@unlink($uploadFile);
					die($this->error("上传时间超时，如果您的网络较慢，您可以选择小文件上传"));
				}
			}
			$this->_savedPath = $saveFullPath;
			
			return $this->_savedPath;
		
        }

        function getInfo($photo) {
                $imageInfo = getimagesize($photo);
                $imgInfo["width"] = $imageInfo[0];
                $imgInfo["height"] = $imageInfo[1];
                $imgInfo["type"] = $imageInfo[2];
                $imgInfo["name"] = basename($photo);
                return $imgInfo;
        }

        function smallImg($photo,$width=200,$height=200,$uid=0) {
                $imgInfo = $this->getInfo($this->_savedPath);
				//判断s上传类别，头像的话不需要加thumb
				switch($this->_ntype){
					case 'point':
						 $newName = substr($imgInfo["name"],0,strrpos($imgInfo["name"], "."))."_thumb.".$this->_ext;//新图片名称
					break;
					case 'icon':
					     //$newName = $this->_saveName;
					     $newName = $uid.'_thumb';
					break;

					case 'album':
						$newName = substr($imgInfo["name"],0,strrpos($imgInfo["name"], "."))."_thumb.".$this->_ext;
					break;
					case 'square':
						$newName = substr($imgInfo["name"],0,strrpos($imgInfo["name"], "."))."_thumb.".$this->_ext;
					break;
				}
				
				$photo = $this->_savedPath;
                if($imgInfo["type"] == 1) {
                        $img = imagecreatefromgif($photo);
                } elseif($imgInfo["type"] == 2) {
                        $img = imagecreatefromjpeg($photo);
                } elseif($imgInfo["type"] == 3) {
                        $img = imagecreatefrompng($photo);
                } elseif($imgInfo["type"] == 6) {
                        $img = Imagecreatefrombmp($photo);
                } else {
                        $img = "";
                }
                if(empty($img)) return false;
				$width = ($width > $imgInfo["width"]) ? $imgInfo["width"] : $width; 
                $height = ($height > $imgInfo["height"]) ? $imgInfo["height"] : $height; 
                $srcW = $imgInfo["width"]; 
                $srcH = $imgInfo["height"]; 
                if ($srcW * $width > $srcH * $height) {
                        $height = round($srcH * $width / $srcW);
                } else {
                        $width = round($srcW * $height / $srcH);
                }
                if (function_exists("imagecreatetruecolor")) {
                        $newImg = imagecreatetruecolor($width, $height);
                        ImageCopyResampled($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
                } else {
                        $newImg = imagecreate($width, $height);
                        ImageCopyResized($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
                }

				if (file_exists($this->_savePath. $newName)) @unlink($this->_savePath.$newName);
				ImageJPEG($newImg,$this->_savePath. $newName);
				ImageDestroy($newImg);
                ImageDestroy($img);
			//dbg($newName);
				return $this->_savePath.$newName;
        }


        function waterMark($photo,$text,$width = 200,$height=200) {
                $imgInfo = $this->getInfo($photo);
                $photo = $this->picturesFolder."/".$photo;
                $newName = substr($imgInfo["name"], 0, strrpos($imgInfo["name"], ".")) . "_mark.".$this->type;
                switch ($imgInfo["type"]) {
                        case 1:
                                $img = imagecreatefromgif($photo);
                        break;
                        case 2:
                                $img = imagecreatefromjpeg($photo);
                        break;
                        case 3:
                                $img = imagecreatefrompng($photo);
                        break;
                        default:
                                return False;
                }
                if (empty($img)) return False;
                $width = ($this->maxWidth > $imgInfo["width"]) ? $imgInfo["width"] : $this->maxWidth; 
                $height = ($this->maxHeight > $imgInfo["height"]) ? $imgInfo["height"] : $this->maxHeight; 
                $srcW = $imgInfo["width"]; 
                $srcH = $imgInfo["height"]; 
                if ($srcW * $width > $srcH * $height) {
                        $height = round($srcH * $width / $srcW);
                } else {
                        $width = round($srcW * $height / $srcH);
                }
                if (function_exists("imagecreatetruecolor")) {
                        $newImg = imagecreatetruecolor($width, $height);
                        ImageCopyResampled($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
                } else {
                        $newImg = imagecreate($width, $height);
                        ImageCopyResized($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
                }
                
                $white = imageColorAllocate($newImg, 255, 255, 255);
                $black = imageColorAllocate($newImg, 0, 0, 0);
                $alpha = imageColorAllocateAlpha($newImg, 230, 230, 230, 40);
                ImageFilledRectangle($newImg, 0, $height-26, $width, $height, $alpha);
                if($width<135){
                	ImageTTFText($newImg, 8, 0, 0, $height-10, $black, $this->fontType, $text);
                }
                else {
                	ImageTTFText($newImg, 14, 0, $width-135, $height-10, $black, $this->fontType, $text);
                }
                
                if($this->toFile) {
                        if (file_exists($this->picturesFolder."/".$newName)) @unlink($this->picturesFolder."/".$newName);
                        ImageJPEG($newImg,$this->picturesFolder."/".$newName);
                        return $this->picturesFolder."/".$newName;
                } else {
                        ImageJPEG($newImg);
                }
                ImageDestroy($newImg);
                ImageDestroy($img);
                return $newName;
        }


            function waterThumbMark($photo,$text,$width = 200,$height = 200) {
                $imgInfo = $this->getInfo($photo);
                $photo = $this->picturesFolder."/".$photo;
                $newName = substr($imgInfo["name"], 0, strrpos($imgInfo["name"], ".")) . "_thumb.".$this->type;
                switch ($imgInfo["type"]) {
                        case 1:
                                $img = imagecreatefromgif($photo);
                        break;
                        case 2:
                                $img = imagecreatefromjpeg($photo);
                        break;
                        case 3:
                                $img = imagecreatefrompng($photo);
                        break;
                        default:
                                return False;
                }
                if (empty($img)) return False;
				$width = ($width > $imgInfo["width"]) ? $imgInfo["width"] : $width; 
                $height = ($height > $imgInfo["height"]) ? $imgInfo["height"] : $height; 
                $srcW = $imgInfo["width"]; 
                $srcH = $imgInfo["height"]; 
                if ($srcW * $width > $srcH * $height) {
                        $height = round($srcH * $width / $srcW);
                } else {
                        $width = round($srcW * $height / $srcH);
                } 
                if (function_exists("imagecreatetruecolor")) {
                        $newImg = imagecreatetruecolor($width, $height);
                        ImageCopyResampled($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
                } else {
                        $newImg = imagecreate($width, $height);
                        ImageCopyResized($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
                }
                
                $white = imageColorAllocate($newImg, 255, 255, 255);
                $black = imageColorAllocate($newImg, 0, 0, 0);
                $alpha = imageColorAllocateAlpha($newImg, 230, 230, 230, 40);
                ImageFilledRectangle($newImg, 0, $height-18, $width, $height, $alpha);
               	ImageTTFText($newImg, 10, 0, $width-90, $height-5, $black, $this->fontType, $text);
                
                if($this->toFile) {
                        if (file_exists($this->picturesFolder."/".$newName)) @unlink($this->picturesFolder."/".$newName);
                        ImageJPEG($newImg,$this->picturesFolder."/".$newName);
                        return $this->picturesFolder."/".$newName;
                } else {
                        ImageJPEG($newImg);
                }
                ImageDestroy($newImg);
                ImageDestroy($img);
                return $newName;
        }

}
?>
